package com.vim.modules.web.service;

import com.vim.common.utils.IdGen;
import com.vim.common.base.CrudServiceImpl;
import com.vim.modules.web.model.SysMenu;
import com.vim.modules.web.dao.SysMenuMapper;
import com.vim.modules.web.model.SysRoleMenu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysMenuService extends CrudServiceImpl<SysMenu> {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Autowired
    public SysMenuService(SysMenuMapper mapper) {
        super(mapper);
    }

    @Override
    public int save(SysMenu entity) {
        entity.setMenuId(IdGen.uuid());
        return super.save(entity);
    }

    /**
     * 查询角色权限
     * @param roleId
     */
    public List<SysMenu> findRoleMenuList(String roleId){
        return sysMenuMapper.findRoleMenuList(roleId);
    }

    /**
     * 保存角色权限
     * @param roleId
     * @param menuIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleMenu(String roleId, String menuIds) {
        sysMenuMapper.deleteRoleMenu(roleId);
        String[] menuIdList = menuIds.split(",");
        for(String menuId:menuIdList){
            if(StringUtils.isNoneBlank(menuId)){
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(menuId);
                sysMenuMapper.saveRoleMenu(sysRoleMenu);
            }
        }
    }

    /**
     * 获取用户所有权限菜单
     * @param userId
     */
    public List<SysMenu> findUserMenuList(String userId) {
        return sysMenuMapper.findUserMenuList(userId);
    }

    /**
     * 删除菜单及其子菜单
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteMenu(String id) {
        SysMenu sysMenu = find(id);
        if(null != sysMenu){
            if(sysMenu.getMenuLevel() == 1){
                sysMenuMapper.deleteSubMenu(id);
            }
            sysMenuMapper.delete(id);
        }
    }

}

